/*****************
 * a class that loads an xml file into flash
 */

package ch.sfug.net.loader {
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import ch.sfug.net.loader.AbstractLoader;	

	public class XMLLoader extends AbstractLoader {

		private var xml:XML;
		private var loader:URLLoader;

		public function XMLLoader( url:String = null ) {

			super(new URLRequest(url));

			xml = new XML();
            
			loader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, xmlLoaded);
			loader.addEventListener(Event.OPEN, onLoadStarts);
			loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, delegate);
			loader.addEventListener(ProgressEvent.PROGRESS, delegate);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, delegate);
			loader.addEventListener(IOErrorEvent.IO_ERROR, delegate);
		}

		
		/**
		 * loads an xml file from the specified url. if you specified it already in the constructor you can omit it.
		 */
		override public function load( request:URLRequest = null ):void {
			this.request = request;
			loader.load(this.request);
		}

		
		/**
		 * stops the download of the cssfile
		 */
		public override function stop(  ):void {
			if( running ) loader.close();
			onLoadEnds();
		}

		
		/**
		 * returns the xml
		 */
		public function getResult():XML {
			return xml;
		}

		
		/**
		 * catch the event when the xml is loaded and assign it.
		 */
		private function xmlLoaded( event:Event ):void {
			xml = XML(loader.data);
			super.onLoadEnds(event);
		}

		
		/**
		 * simply delegates the event
		 */
		private function delegate( event:Event ):void {
			dispatchEvent(event);
		}
		
		override public function get bytesLoaded():Number
		{
			return loader.bytesLoaded;
		}
		override public function get bytesTotal():Number
		{
			return loader.bytesTotal;
		}
	}
}


